<template>
	<view class="cu-form-group margin-top">
		<view class="grid col-4 grid-square flex-sub">
			<view class="bg-img" v-for="(item,index) in list" :key="index" @tap="ViewImage" :data-url="list[index]">
				<image :src="list[index]" mode="aspectFill"></image>
				<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
					<text class='cuIcon-close'></text>
				</view>
			</view>
			<view class="solids" @tap="ChooseImage" v-if="list.length<4">
				<text class='cuIcon-cameraadd'></text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			imgList: {
				type: Array,
				default: []
			},
			// 配置
			config:{
				type: Object,
			}
		},
		data() {
			return {
				list: this.imgList
			}
		},
		methods: {
			ChooseImage() {
				let that = this
				uni.chooseImage({
					count: that.config.count, //默认9
					sizeType: that.config.sizeType, //可以指定是原图还是压缩图，默认二者都有
					
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: that.config.url, //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: that.config.upload_name,
							header:that.config.header,
							success: (uploadFileRes) => {
								const data = JSON.parse(uploadFileRes.data)
								if (that.list.length != 0) {
									that.list = that.list.concat(data.result[0].file)
								} else {
									that.list = that.list.concat(data.result[0].file)
								}
								that.$emit('update:imgList', that.list)
							}
						});

					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.list,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				let that = this
				uni.showModal({
					title: '删除',
					content: '确定要删除图片？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							that.list.splice(e.currentTarget.dataset.index, 1)
							that.$emit('update:imgList', that.list)
						}
					}
				})
			},
		},
		watch:{
			imgList(val){
				this.list = val
			}
		}

	}
</script>

<style>

</style>
